package mx.com.fractal.ristorante.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import mx.com.fractal.ristorante.dao.ReservacionDAO;
import mx.com.fractal.ristorante.dto.MesaDTO;
import mx.com.fractal.ristorante.dto.ReservacionDTO;
import mx.com.fractal.ristorante.util.ParamSrcUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

@Repository("reservacionDAO")
public class ReservacionDAOImpl implements ReservacionDAO {
	
	private static final Logger logger=Logger.getLogger(ReservacionDAOImpl.class);

	private static final String INSERT = "INSERT INTO ristorant_e.reservacion("
			+ "id_restaurante,id_cliente,num_personas,fecha_reservacion,minutos_bloqueo,minutos_tolerancia) "
			+ "values(:getIdRestaurante,:idCliente,:getNumPersonas,:getFechaReservacion,"
			+ ":getMinutosBloqueo,:getMinutosTolerancia)";
	
	@Autowired
	private NamedParameterJdbcTemplate jdbc;
	
	public Integer save(ReservacionDTO reservacion) {
		MapSqlParameterSource parameters = ParamSrcUtil
				.getParams(reservacion);
		
		
		parameters.addValue("idCliente", reservacion.getClienteDTO().getIdCliente());
		GeneratedKeyHolder holder = new GeneratedKeyHolder();
		jdbc.update(INSERT, parameters, holder);
		
		return (Integer) holder.getKeys().get("id_reservacion");
	}
	
	public int[] saveReservacionMesa(int idReservacion,Set<MesaDTO> mesas) throws Exception{
		SqlParameterSource []parameterSources = new SqlParameterSource[mesas.size()];
		int i=0;
		for(MesaDTO mesa: mesas){
			MapSqlParameterSource map = new MapSqlParameterSource();
			map.addValue("idMesa", mesa.getIdMesa());
			map.addValue("idReservacion", idReservacion);
			parameterSources[i++] = map;
			logger.trace("Agregando parametros a insertar --> " + map);
		}
		
		return jdbc.batchUpdate("INSERT INTO ristorant_e.reservacion_mesa (id_reservacion,id_mesa) "
				+ "VALUES(:idReservacion,:idMesa)", parameterSources);
	}

	public List<ReservacionDTO> getAllBy(ReservacionDTO conditions)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}